package com.itheima.ssm.controller;

import com.itheima.ssm.domain.Role;
import com.itheima.ssm.domain.UserInfo;
import com.itheima.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {


    @Autowired
    private IUserService iUserService;

    @RequestMapping("/findAll.do")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<UserInfo> userInfoList = iUserService.findAll();
        mv.addObject("userInfoList",userInfoList);
        mv.setViewName("user-list");
        return mv;
    }

    @RequestMapping("/save.do")
    public String save(UserInfo userInfo) throws Exception {
        iUserService.save(userInfo);
        return "redirect:findAll.do"; // 重定向到查询所有用户信息页面
    }

    /**
     * 查询用户的详细信息
     * @param userId
     * @return
     */
    @RequestMapping("/findById.do")
    public ModelAndView findById(@RequestParam(name = "id",required = true) int userId) throws Exception {
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo = iUserService.findById(userId);
        mv.addObject("userInfo",userInfo);
        mv.setViewName("user-list");
        return mv;
    }

    /**
     * 1. 查询用户的数据库中没有的角色
     * 2. 然后跳转到role-add.jsp页面，为用户添加角色
     * 将模型与数据返回到jsp页面上，显示用户可以勾选的角色
     * 之后用户就可以添加角色了
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id",required = true) int userId) throws Exception {
        // 1. 根据用户id查找出用户信息，封装到UserInfo实体Bean中
        UserInfo userInfo = iUserService.findById(userId);
        // 2. 找到当前用户没有的角色
        List<Role> othersList = iUserService.findOtherRoles(userId);
        // 3. 创建模型数据对象
        ModelAndView mv = new ModelAndView();
        mv.addObject("user",userInfo);
        mv.addObject("roleList",othersList);
        mv.setViewName("user-role-add");
        return mv;
    }

    /**
     * 将添加的角色存放到数据库中关联表users_role中
     * @return
     * @param userId : 需要添加角色的用户id
     * @param roleIds: 需要添加的角色id列表
     */
    @RequestMapping("/addRoleToUser")
    public void addRoleToUser(@RequestParam(name = "id") int userId,String[] roleIds) throws Exception{
        iUserService.addRoleToUser(userId,roleIds);
    }
}
